package com.leige.webconfig.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.leige.utils.tool.Context;

/**
 * 记录收到的http请求.
 * 
 * @author Administrator
 *
 */
public class LoggerInterceptor extends HandlerInterceptorAdapter {

	private final static Logger logger = LoggerFactory.getLogger(LoggerInterceptor.class);

	@Override
	public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
		if (logger.isInfoEnabled()) {
			String url = request.getRequestURI();
			if (filterLogger(url)) {
				logger.info("已接受到请求:" + url);
			}
		}
		Context.setRequest(request);
		Context.setResponse(response);
		return true;
	}

	private boolean filterLogger(final String url) {
		if (url.endsWith(".do") || url.endsWith(".json") || url.indexOf('.') == -1) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) throws Exception {
		if (logger.isInfoEnabled()) {
			String url = request.getRequestURI();
			if (filterLogger(url)) {
				logger.info("请求已结束:" + url);
			}
		}
		Context.remove();
	}
}